package com.hgxd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hgxd.entity.authentication.CustomUser;
import com.hgxd.entity.pojo.SysMenu;
import com.hgxd.entity.pojo.SysUser;
import com.hgxd.exception.ServiceException;
import com.hgxd.mapper.SysMenuMapper;
import com.hgxd.result.ResultCodeEnum;
import com.hgxd.service.SysUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wtf
 * @create 2023-07-24 17:48
 * @description : 自定义登录认证
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource(name = "SysUserServiceImpl")
    private SysUserService userService;

    @Value("${server.port}")
    private String port;


    @Resource
    private RestTemplate restTemplate;
    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.getOne(new QueryWrapper<SysUser>().eq("username", username));
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        if (sysUser.getStatus() == 0) {
            throw new RuntimeException("状态非法");
        }

//        添加日志
        Boolean b = restTemplate.getForObject("http://localhost:" + port + "/api/setOperationForLogin?username={username}"
                , Boolean.class
                , username);
        if (Boolean.FALSE.equals(b)) {
            throw new ServiceException(ResultCodeEnum.FAIL, "用户登录日志无法记录");
        }
        // 获取特定用户的菜单记录列表 此sysMenuList是有菜单（一级菜单和二级菜单）有按钮的
        List<SysMenu> sysMenuList = sysMenuMapper.getSysMenuListByUserId(sysUser.getUserId());

//        // 获取对应角色需要的菜单列表（树型）
//        List<SysMenu> menuTreeList = getMenuList(sysMenuList);
//        sysUser.setMenuList(menuTreeList);

        // 此userPermsList是只有按钮
        List<String> userPermsList = sysMenuList.stream().filter(sysMenu -> sysMenu.getType() == 2)
                .map(SysMenu::getPerms).collect(Collectors.toList());
//        System.out.println("userPermsList = " + userPermsList);
//        List<String> userPermsList = sysUserService.getUserBtnPersByUserId(sysUser.getId());
        sysUser.setUserPermsList(userPermsList);

        return new CustomUser(sysUser);

    }

//    /**
//     * 获取树形结构，以供前端动态路由
//     *
//     * @param sysMenuList
//     * @return
//     */
//    private List<SysMenu> getMenuList(List<SysMenu> sysMenuList) {
//        // 去重+去按钮
//        List<SysMenu> allList = MenuUtils.removeRepeat(sysMenuList)
//                .stream()
//                .filter(menu -> menu.getType() != 2)
//                .collect(Collectors.toList());
//        //获取父id 即目录
//        List<SysMenu> parentMenuList = allList.stream()
//                .filter(sysMenu -> sysMenu.getParentId() == 0)
//                .collect(Collectors.toList());
//
//        return new SysMenuServiceImpl().setTree(allList,parentMenuList);
//    }
}
